import datetime
import time


def transform_json(sourcefilepath, destfilepath):

    """
    
    :param sourcefilepath: 
    :param destfilepath: 
    :return: 
    """
    with open(sourcefilepath, "r", encoding="utf-8") as fd_r:
        line_list = fd_r.readlines()

    json_string = line_list[0].strip("[").strip("]")
    count = json_string.count("}")
    index = json_string.index("}")
    i = 0
    line1_list = []
    with open(destfilepath, "w", encoding="utf-8") as fd_w:
        while i < count:
            line1 = json_string[0:index + 1]
            line1_list.append(line1)
            json_string = json_string[index + 2:]
            count = json_string.count("}")
            if (count == 0):
                break
            index = json_string.index("}")
            fd_w.write(line1)
            fd_w.write("\n")


def transform_json1(sourcefilepath, destfilepath):
    with open(sourcefilepath, "r", encoding="utf-8") as fd_r:
        line_list = fd_r.readlines()
    json_string = line_list[0].strip("[").strip("]")

    with open(destfilepath, "w", encoding="utf-8") as fd_w:
        for line in json_string.strip().split("}"):
            line = line.strip() + '}'
            if line.startswith(","):
                fd_w.write(line[1:])
            else:
                fd_w.write(line)
            # fd_w.write("\r")


def main():
    sourcefilepath = "../data/MealRatings_201705_201706.json"
    destfilepath = "../data/MealRatings.json"
    destfilepath1 = "../data/MealRatings1.json"
    starttime = datetime.datetime.now()
    transform_json(sourcefilepath, destfilepath)
    endtime = datetime.datetime.now()
    print("transform_json func elapsed time: ", (endtime - starttime).microseconds)
    time.sleep(5)
    starttime = datetime.datetime.now()
    transform_json1(sourcefilepath, destfilepath1)
    endtime = datetime.datetime.now()
    print("transform_json1 func elapsed time: ", (endtime - starttime).microseconds)


if __name__ == '__main__':
    main()
